<template>
  <div>
    <el-dialog title="新增模块" v-model="isAddModule" width="30%">
      <el-form
        :model="newModule"
        ref="moduleForm"
        :rules="moduleRules"
        label-width="100px"
        :inline="false"
        size="default"
      >
        <el-form-item label="模块名" prop="name">
          <el-input v-model="newModule.name" clearable></el-input>
        </el-form-item>
        <!-- 自动化类型只有web和api两种，所以用单选框就好 -->
        <el-form-item label="自动化类型" prop="type">
          <el-radio-group v-model="newModule.type">
            <el-radio label="web">web </el-radio>
            <el-radio label="api">接口 </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="isAddModule = false">取消</el-button>
          <el-button type="primary" @click="addModule">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-row>
      <el-col :span="5">
        <el-card
          shadow="always"
          :body-style="{
            padding: '20px',
            'overflow-y': 'auto',
            height: 'calc(100vh - 170px)',
          }"
        >
          <template #header>
            <el-row>
              <el-col :span="12"
                ><span style="font-size: larger; font-weight: bold"
                  >模块列表</span
                ></el-col
              >
              <el-col :span="12" style="text-align: right">
                <el-button
                  type="success"
                  size="default"
                  :icon="Plus"
                  @click="openModuleAdder"
                  >新增</el-button
                ></el-col
              >
            </el-row>
          </template>
          <ModuleCard
            v-for="sunnyModule in moduleList"
            :key="sunnyModule.id"
            :module="sunnyModule"
            :class="{
              selectedModule: sunnyModule.id === moduleStore.selectedModule.id,
            }"
            @click="selectModule(sunnyModule)"
            @delete-module="deleteModule"
            @update-module="updateModule($event, sunnyModule)"
          ></ModuleCard>
        </el-card>
      </el-col>
      <el-col :span="19">
        <RouterView> </RouterView>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import type { SunnyModule } from "@/types/sunnyModule/type";
import { ref, onMounted } from "vue";
import {
  listModuleApi,
  addModuleApi,
  deleteModuleApi,
  updateModuleApi,
} from "@/api/sunnymodule";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import ModuleCard from "./ModuleCard.vue";
import router from "@/router";
import { useModuleStore } from "@/stores/sunnyModuleStore";
import { onBeforeRouteUpdate } from "vue-router";
import { storeToRefs } from "pinia";

//通过store来全局管理要用的module
const moduleStore = useModuleStore();

const { moduleList } = storeToRefs(moduleStore);

//控制新增模块窗口的弹出
const isAddModule = ref(false);
//新增模块的数据
const newModule = ref<SunnyModule>({ id: 0, name: "", type: "" });
//模块表单的校验规则
const moduleRules = ref<FormRules>({
  //模块名限制一下长度
  name: [
    { required: true, message: "模块名必填", trigger: "blur" },
    {
      min: 2,
      max: 15,
      message: "模块名称请限制在2到15位之间",
      trigger: "blur",
    },
  ],
  type: [{ required: true, message: "自动化类型必选", trigger: "blur" }],
});
//定义表单组件模板
const moduleForm = ref<FormInstance>();

onBeforeRouteUpdate(() => {
  listModules();
});

onMounted(() => {
  listModules();
});

//进入模块组件的时候，默认选中之前选中的模块
function listModules() {
  listModuleApi()
    .then(({ data }) => {
      moduleList.value = data;
      //判断一下列表是否为空，如果有内容，选中moduleStore中之前已经选中的模块。
      if (moduleList.value.length > 0) {
        selectModule(moduleStore.selectedModule);
      }
    })
    .catch((error) => {
      ElMessage.error("获取模块列表出现了错误" + error);
    });
}

/**选中模块 */
function selectModule(sunnyModule: SunnyModule) {
  moduleStore.selectedModule = sunnyModule;
  router.replace({
    name: "caseInModule",
    params: { moduleId: sunnyModule.id },
  });
}

/**
 * 打开新增弹窗
 */
function openModuleAdder() {
  isAddModule.value = true;
}

/**
 * 新增module模块
 */
function addModule() {
  isAddModule.value = false;
  if (!moduleForm.value) return;
  moduleForm.value.validate((valid) => {
    if (valid) {
      //使用内联模板字符串
      // ElMessage.info(`要添加的module是${JSON.stringify(newModule.value)}`);
      addModuleApi(newModule.value)
        .then(() => {
          ElMessage.success("新增成功");
        })
        //新增完之后，重新刷新数据
        .then(() => {
          listModules();
        });
    } else {
      ElMessage.error("请按规则填写模块名和自动化类型");
      //重置表单数据
      moduleForm.value?.resetFields();
    }
  });
}
/**
 * 修改模块信息,updateModule需要接收子组件传来的moduleName,以及父组件自己传参的module对象
 */
function updateModule(moduleName: string, sunnyModule: SunnyModule) {
  console.log("修改的模块是", sunnyModule);
  //只有修改的值和原本的不相等的时候才提交修改
  if (sunnyModule.name !== moduleName) {
    sunnyModule.name = moduleName;
    console.log("要提交修改的数据是", sunnyModule);

    updateModuleApi(sunnyModule)
      .then(() => {
        ElMessage.success("修改用例成功");
      })
      .then(() => {
        listModules();
      });
  }
}

/**删除模块 */
function deleteModule(sunnyModule: SunnyModule) {
  ElMessage.info(`要删除的模块是${sunnyModule}`);
  console.log("修改的模块是", sunnyModule);
  deleteModuleApi(sunnyModule.id)
    .then(() => {
      ElMessage.success(`删除模块${sunnyModule.name}}成功`);
    })
    .then(() => {
      if (sunnyModule.id == moduleStore.selectedModule.id) {
        moduleStore.selectedModule = {
          id: -1,
          name: "请选择模块",
          type: "无类型",
        };
      }
      listModules();
    });
}
</script>

<style scoped>
/* 直接给所有的el-col都加一个padding来调整间距 */
.el-col {
  padding: 2px 5px;
}

.selectedModule {
  background-color: #a0cfff;
}
</style>
